from django.shortcuts import render,redirect
from django.contrib.auth import get_user_model

from django.http.response import HttpResponse
from django.contrib.auth import authenticate,login,logout
from django.urls import reverse_lazy
from XMGM.models import Messagetable
# Create your views here.
User = get_user_model()
messagetable = get_user_model()

return_url = reverse_lazy('xmgm')   #重定向地址url 写这个用来登录成功或者注册成功后返回首页

#注册  并以注册账号登陆，回到首页
def create_user(request):
    user = request.POST['username']
    password = request.POST['password']
    email = request.POST['email']
    phone_num = request.POST['tel']
    user = User.objects.create_user(username=user,password=password,email=email,phone_num=phone_num)
    if user:
        login(request,user)
        # return HttpResponse('注册成功')
    return redirect(return_url)


#登录 并跳转首页首页
def user_login(request):
    username = request.POST['username']
    password = request.POST['password']

    user = authenticate(username=username,password=password)
    if not user:
        return HttpResponse('登录失败')
    login(request,user) #登陆成功的cooki写入
    print('登录成功')
    return redirect(return_url) #重定向  返回首页

#登出 返回首页
def user_logout(request):
    logout(request) #退出

    return redirect(return_url)
    # return HttpResponse('退出成功')

# 评论
def Message(request):
    name = request.POST['name']
    email = request.POST['email']
    message = request.POST['message']

    # messagetable.objects.Messagetable(name=name,email=email,message=message)
    msg = Messagetable()
    msg.Message = message
    msg.name = name
    msg.email = email
    msg.save()
    return HttpResponse('评论成功')
